package com.example.home7;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.room.Database;

import java.util.List;

public class Room extends Fragment {
    private TextView textView;
    public Room() {
        super(R.layout.sqljiemian);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        textView = getView().findViewById(R.id.textView6);
        EditText e1 = getView().findViewById(R.id.textView3);
        EditText e2 = getView().findViewById(R.id.textView5);
        MyRoomDatabase db;
        db = MyRoomDatabase.getInstance(getActivity());
        getView()
        .findViewById(R.id.button6)
        .setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                db.roomDao().insert(new User(e1.getText().toString(),
                        Integer.parseInt(e2.getText().toString())));
                showUsers(db.roomDao().getAll());
            }
        });
        getView()
        .findViewById(R.id.button7)
        .setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUsers(db.roomDao().getAllByAge(19));
            }
        });
    }
    private void showUsers(List<User> users) {
        StringBuilder stringBuilder = new StringBuilder();
        for (User user: users) {
            stringBuilder
            .append("id:")
            .append(user.id)
            .append("    username:")
            .append(user.username)
            .append( "   age:")
            .append(user.age)
            .append("\n");
        }
        textView.setText(stringBuilder.toString());
    }
}
